
<template>
  <div class="app-container">
    <el-card>
      <div slot="header" style="margin-bottom: 15px">
        <el-button plain @click="dialogTableVisible = true">
          订单日志
        </el-button>

        <el-button plain @click="openAddCommentDialog">
          添加备注
        </el-button>

        <!-- 打印发货单按钮 -->
        <el-button type="danger" plain style="float: right;" @click="openPrintDialog">
          打印发货单
        </el-button>

        <el-dialog v-model="dialogTableVisible" title="订单日志" width="800">
          <el-table :data="gridData">
            <el-table-column property="date" label="时间" width="150" />
            <el-table-column property="name" label="操作者" width="200" />
            <el-table-column property="name" label="操作类型" width="200" />
            <el-table-column property="name" label="日志" width="200" />
          </el-table>
        </el-dialog>

        <el-dialog v-model="dialogFormVisible" title="添加备注" width="500">
          <el-form :model="form">
            <el-form-item label="订单备注" :label-width="formLabelWidth" prop="orderComment">
              <el-input v-model="form.orderComment" autocomplete="off" />
            </el-form-item>
          </el-form>
          <template #footer>
            <div class="dialog-footer">
              <el-button @click="dialogFormVisible = false">关闭</el-button>
              <el-button type="primary" @click="handleUpdate">
                确认
              </el-button>
            </div>
          </template>
        </el-dialog>

        <!-- 打印发货单模态框 -->
        <el-dialog v-model="printDialogVisible" title="打印发货单" width="600" :close-on-click-modal="false">
          <div class="print-content">
            <div class="print-header">
              <div class="print-controls">
                <el-button size="small" @click="toggleSensitiveInfo">
                  {{ hideSensitiveInfo ? '显示敏感信息' : '隐藏敏感信息' }}
                </el-button>
              </div>
            </div>

            <div class="print-body" ref="printRef">
              <div class="delivery-info">
                <div class="info-item">
                  <label>收件人:</label>
                  <span v-if="!hideSensitiveInfo">{{ orderDetail.username || '未填写' }}</span>
                  <span v-else>***</span>
                </div>
                <div class="info-item">
                  <label>收货地址:</label>
                  <span v-if="!hideSensitiveInfo">{{ orderDetail.useraddress || '未填写' }}</span>
                  <span v-else>***</span>
                </div>
              </div>

              <div class="product-info">
                <h4>商品信息</h4>
                <div class="product-item">
                  <div class="product-name">{{ orderDetail.goodsname || '商品名称' }}</div>
                  <div class="product-specs">{{ orderDetail.goodsSpecs || '规格' }}</div>
                  <div class="product-quantity">数量: {{ orderDetail.goodsnumber || 1 }}</div>
                </div>
              </div>

              <div class="order-info">
                <div class="info-item">
                  <label>订单号:</label>
                  <span>{{ orderDetail.orderNumber }}</span>
                </div>
                <div class="info-item">
                  <label>下单时间:</label>
                  <span>{{ orderDetail.orderPayTime }}</span>
                </div>
              </div>
            </div>
          </div>

          <template #footer>
            <div class="dialog-footer">
              <el-button @click="printDialogVisible = false">关闭</el-button>
              <el-button type="danger" @click="downloadDeliveryNote">下载发货单</el-button>
            </div>
          </template>
        </el-dialog>
      </div>

      <el-descriptions :column="2" border>
        <el-descriptions-item label="订单号">{{ orderDetail.orderNumber }}</el-descriptions-item>
        <el-descriptions-item label="订单来源">PC端</el-descriptions-item>
        <el-descriptions-item label="订单备注">{{ orderDetail.orderComment || '无' }}</el-descriptions-item>
        <el-descriptions-item label="收货地址">
          {{ orderDetail.username+" "+orderDetail.userphone+" "+orderDetail.useraddress}}
        </el-descriptions-item>
        <el-descriptions-item label="订单状态">
          <el-tag :type="getStatusTagType(orderDetail.orderStatus)">
            {{ getStatusText(orderDetail.orderStatus) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="下单时间">{{ orderDetail.orderPayTime }}</el-descriptions-item>
        <el-descriptions-item label="发票抬头">{{ orderDetail.username || '未开票' }}</el-descriptions-item>
        <el-descriptions-item label="发票内容">商品明细</el-descriptions-item>
        <el-descriptions-item label="发票金额">¥{{ (orderDetail.goodsnumber || 0) * (orderDetail.goodsprice || 0) }}</el-descriptions-item>
        <el-descriptions-item label="是否开票">未开</el-descriptions-item>
      </el-descriptions>

      <div style="margin-top: 20px; text-align: center;">
        <el-button @click="goBack">返回</el-button>
      </div>
    </el-card>
  </div>
  <el-table :data="[orderDetail]" style="padding: 20px">
    <el-table-column label="商品" width="240">
      <template #default="{ row }">
        <div style="display: flex">
        <img :src="row.goodsimg" style="width: 100px;height: 100px"/>
          <div style="margin-left: 20px">
        {{ row.goodsname  }}
        {{ row.goodsSpecs  }}
          </div>
        </div>
      </template>
    </el-table-column>
    <el-table-column label="优惠金额" width="180">
      <template #default>
        {{0}}
      </template>
    </el-table-column>
    <el-table-column label="单价" width="180">
      <template #default="{ row }">
        {{ row.goodsprice || row.goodsspecs }}
      </template>
    </el-table-column>
    <el-table-column prop="goodsnumber" label="数量"  />
    <el-table-column label="小计" width="180">
      <template #default="{ row }">
        {{ (row.goodsnumber || 0) * (row.goodsprice || row.goodsspecs || 0) }}
      </template>
    </el-table-column>
  </el-table>

  <div style="padding: 20px;float: right" >
    <div>商品总额: {{ (orderDetail.goodsnumber ) * (orderDetail.goodsprice ) }}</div>
    <div>运费: {{ orderDetail.orderPostPrice }}</div>
    <div>应付金额: {{ (orderDetail.goodsnumber ) * (orderDetail.goodsprice ) + (orderDetail.orderPostPrice || 0) }}</div>
  </div>
</template>

<script setup>
import { ref, onMounted, reactive } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { getOrderst, updateOrderst } from "@/api/zmhshop/orderst"
import { ElMessage } from 'element-plus'

const dialogTableVisible = ref(false);
const dialogFormVisible = ref(false);
const printDialogVisible = ref(false);
const hideSensitiveInfo = ref(false);
const printRef = ref(null);
const formLabelWidth = '140px';

const form = reactive({
  orderComment: '' // 只保留需要的字段
});

const gridData = [
  {
    date: '2016-05-02',
    name: 'John Smith',
    address: 'No.1518, Jinshajiang Road, Putuo District'
  },
  {
    date: '2016-05-04',
    name: 'John Smith',
    address: 'No.1518, Jinshajiang Road, Putuo District'
  },
  {
    date: '2016-05-01',
    name: 'John Smith',
    address: 'No.1518, Jinshajiang Road, Putuo District'
  },
  {
    date: '2016-05-03',
    name: 'John Smith',
    address: 'No.1518, Jinshajiang Road, Putuo District'
  }
];

const tableData = [
  {
    goods_specs: '2016-05-03',
    goodsprice: '2016-05-03',
    goodsnumber: 'Tom',
  },
];

const route = useRoute()
const router = useRouter()

const orderDetail = ref({})

// 打开打印发货单对话框
const openPrintDialog = () => {
  printDialogVisible.value = true
  hideSensitiveInfo.value = false
}

// 切换敏感信息显示
const toggleSensitiveInfo = () => {
  hideSensitiveInfo.value = !hideSensitiveInfo.value
}

// 下载发货单
const downloadDeliveryNote = () => {
  try {
    // 创建发货单内容
    const content = `
发货单

收件人: ${hideSensitiveInfo.value ? '***' : (orderDetail.value.username || '未填写')}
收货地址: ${hideSensitiveInfo.value ? '***' : (orderDetail.value.useraddress || '未填写')}

商品信息:
商品名称: ${orderDetail.value.goodsname || '商品名称'}
规格: ${orderDetail.value.goodsspecs || '规格'}
重量: ${orderDetail.value.goodsspecs || '500克'}
数量: ${orderDetail.value.goodsnumber || 1}

订单信息:
订单号: ${orderDetail.value.orderNumber}
下单时间: ${orderDetail.value.orderPayTime}

---
生成时间: ${new Date().toLocaleString()}
    `.trim()

    // 创建Blob对象
    const blob = new Blob([content], { type: 'text/plain;charset=utf-8' })

    // 创建下载链接
    const url = window.URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url

    // 设置文件名
    const fileName = `发货单_${orderDetail.value.orderNumber || '订单'}_${new Date().getTime()}.txt`
    link.download = fileName

    // 触发下载
    document.body.appendChild(link)
    link.click()

    // 清理
    document.body.removeChild(link)
    window.URL.revokeObjectURL(url)

    ElMessage.success('发货单下载成功')
    printDialogVisible.value = false
  } catch (error) {
    console.error('下载失败:', error)
    ElMessage.error('下载失败，请重试')
  }
}

// 打开添加备注对话框
const openAddCommentDialog = () => {
  form.orderComment = orderDetail.value.orderComment || '' // 初始化表单值
  dialogFormVisible.value = true
}

// 获取订单详情
const getDetail = async () => {
  try {
    const res = await getOrderst(route.query.orderId)
    orderDetail.value = res.data
  } catch (error) {
    console.error('获取订单详情失败:', error)
    ElMessage.error('获取订单详情失败')
  }
}

// 更新订单备注
const handleUpdate = async () => {
  try {
    // 创建更新对象，只更新备注字段
    const updateData = {
      orderId: orderDetail.value.orderId,
      orderComment: form.orderComment
    }

    await updateOrderst(updateData)
    ElMessage.success('备注更新成功')
    dialogFormVisible.value = false
    getDetail() // 刷新数据
  } catch (error) {
    console.error('更新备注失败:', error)
    ElMessage.error('更新备注失败')
  }
}

// 订单状态文本映射
const getStatusText = (status) => {
  const statusMap = {
    0: '待支付',
    1: '已支付',
    2: '已发货',
    3: '已完成',
    4: '已取消'
  }
  return statusMap[status] || '未知状态'
}

// 订单状态标签类型
const getStatusTagType = (status) => {
  const typeMap = {
    0: 'warning',
    1: 'primary',
    2: 'info',
    3: 'success',
    4: 'danger'
  }
  return typeMap[status] || ''
}

// 返回
const goBack = () => {
  router.go(-1)
}

onMounted(() => {
  getDetail()
})
</script>

<style scoped>
.print-content {
  padding: 20px;
}

.print-header {
  display: flex;
  justify-content: flex-end;
  margin-bottom: 20px;
}

.print-body {
  border: 1px solid #ddd;
  padding: 20px;
  background: #fff;
  min-height: 400px;
}

.delivery-info {
  margin-bottom: 30px;
}

.info-item {
  margin-bottom: 15px;
  display: flex;
  align-items: center;
}

.info-item label {
  font-weight: bold;
  min-width: 80px;
  margin-right: 10px;
}

.product-info {
  margin-bottom: 30px;
}

.product-info h4 {
  margin-bottom: 15px;
  color: #333;
  border-bottom: 1px solid #eee;
  padding-bottom: 5px;
}

.product-item {
  background: #f9f9f9;
  padding: 15px;
  border-radius: 5px;
}

.product-name {
  font-weight: bold;
  margin-bottom: 5px;
}

.product-specs {
  color: #666;
  margin-bottom: 5px;
}

.product-weight,
.product-quantity {
  color: #666;
  font-size: 14px;
}

.order-info {
  border-top: 1px solid #eee;
  padding-top: 20px;
}

.dialog-footer {
  text-align: right;
}
</style>